package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Api(tags = "C端用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    JwtProperties jwtProps;

    @PostMapping("/login")
    @ApiOperation("微信登录")
    public Result<UserLoginVO> lightLogin(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户微信登录{}", userLoginDTO.getCode());//获取到前端code码
        //微信登录业务
        User user = userService.wxLogin(userLoginDTO);
        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        //claim的作用就是给jwt传一个用户的唯一标识id，让不同用户最后生成的token不一样
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        //把密钥，appid，userid传进去生成jwt令牌
        String token = JwtUtil.createJWT(jwtProps.getUserSecretKey(), jwtProps.getUserTtl(), claims);
        //用构建器builder将id openid token 给userLoginVo
        UserLoginVO userLoginVO = UserLoginVO.builder().id(user.getId()).openid(user.getOpenid()).token(token).build();
        return Result.success(userLoginVO);

    }

}
